package com.zzyl.nursing.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServletResponse;

import com.zzyl.common.pdf.PdfUtils;
import com.zzyl.common.utils.file.FileUtils;
import com.zzyl.nursing.dto.HealthAssessmentDto;
import com.zzyl.oss.client.OSSAliyunFileStorageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.zzyl.common.annotation.Log;
import com.zzyl.common.core.controller.BaseController;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.enums.BusinessType;
import com.zzyl.nursing.domain.HealthAssessment;
import com.zzyl.nursing.service.IHealthAssessmentService;
import com.zzyl.common.utils.poi.ExcelUtil;
import com.zzyl.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 健康评估Controller
 * 
 * @author shenkunlin
 * @date 2025-01-12
 */
@RestController
@RequestMapping("/nursing/healthAssessment")
@Api(tags = "健康评估的接口")
public class HealthAssessmentController extends BaseController
{
    @Autowired
    private IHealthAssessmentService healthAssessmentService;

    @Autowired
    private OSSAliyunFileStorageService fileStorageService;

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    /****
     * 保存体检报告信息
     * 1、定义Dto，接收参数数据   【名字、身份证号、体检单位、体检报告访问url】
     * 2、根据身份证信息去Redis获取体检报告内容
     * 3、组装Prompt
     * 4、向百度千帆大模型发起请求->返回数据->JSON(结构固定)->封装JSON对应的类(Vo)
     * 5、完善并填充HealthAssessment
     * 6、insert添加
     */
    @PostMapping
    public AjaxResult apply(@RequestBody HealthAssessmentDto dto) throws IOException {
        Long id = healthAssessmentService.insertHealthAssessment(dto);
        return success(id);
    }


    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file,String idCardNo) throws Exception
    {
        try
        {
            //1、实现文件上传
            //文件名--->UUID.后缀
            String originalFilename = file.getOriginalFilename();//abc.jpg
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String filename = UUID.randomUUID().toString()+extension;

            //把文件上传到oss中
            String url = fileStorageService.store(filename, file.getInputStream());
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", url);
            ajax.put("newFileName", FileUtils.getName(filename));
            ajax.put("originalFilename", file.getOriginalFilename());

            //2、解析PDF
            String result = "";
            // 重新获取输入流用于PDF解析
            try (InputStream pdfInputStream = file.getInputStream()) {
                result = PdfUtils.pdfToString(pdfInputStream);
            } catch (Exception e) {
                // 捕获并记录EOFException等字体相关异常，但不中断处理流程
                // 这类异常不影响PDF内容的实际提取
                logger.warn("PDF解析过程中出现字体相关异常，但不影响内容提取: " + e.getMessage(), e);
            }

            //3、将PDF内容存入到Redis       Hash   healthReport
            //                                          idCardNo     体检报告内容
            redisTemplate.opsForHash().put("healthReport",idCardNo,result);
            logger.info("保存PDF内容到Redis成功！");
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 查询健康评估列表
     */
    @ApiOperation("查询健康评估列表")
    @PreAuthorize("@ss.hasPermi('nursing:healthAssessment:list')")
    @GetMapping("/list")
    public TableDataInfo list(HealthAssessment healthAssessment)
    {
        startPage();
        List<HealthAssessment> list = healthAssessmentService.selectHealthAssessmentList(healthAssessment);
        return getDataTable(list);
    }

    /**
     * 导出健康评估列表
     */
    @ApiOperation("导出健康评估列表")
    @PreAuthorize("@ss.hasPermi('nursing:healthAssessment:export')")
    @Log(title = "健康评估", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, HealthAssessment healthAssessment)
    {
        List<HealthAssessment> list = healthAssessmentService.selectHealthAssessmentList(healthAssessment);
        ExcelUtil<HealthAssessment> util = new ExcelUtil<HealthAssessment>(HealthAssessment.class);
        util.exportExcel(response, list, "健康评估数据");
    }

    /**
     * 获取健康评估详细信息
     */
    @ApiOperation("获取健康评估详细信息")
    @PreAuthorize("@ss.hasPermi('nursing:healthAssessment:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@ApiParam(value = "健康评估ID", required = true)
            @PathVariable("id") Long id)
    {
        return success(healthAssessmentService.selectHealthAssessmentById(id));
    }

    /**
     * 新增健康评估
     */
    //@ApiOperation("新增健康评估")
    //@PreAuthorize("@ss.hasPermi('nursing:healthAssessment:add')")
    //@Log(title = "健康评估", businessType = BusinessType.INSERT)
    //@PostMapping
    //public AjaxResult add(@ApiParam(value = "健康评估实体")
    //        @RequestBody HealthAssessment healthAssessment)
    //{
    //    return toAjax(healthAssessmentService.insertHealthAssessment(healthAssessment));
    //}

    /**
     * 修改健康评估
     */
    @ApiOperation("修改健康评估")
    @PreAuthorize("@ss.hasPermi('nursing:healthAssessment:edit')")
    @Log(title = "健康评估", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@ApiParam(value = "健康评估实体")
            @RequestBody HealthAssessment healthAssessment)
    {
        return toAjax(healthAssessmentService.updateHealthAssessment(healthAssessment));
    }

    /**
     * 删除健康评估
     */
    @ApiOperation("删除健康评估")
    @PreAuthorize("@ss.hasPermi('nursing:healthAssessment:remove')")
    @Log(title = "健康评估", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(healthAssessmentService.deleteHealthAssessmentByIds(ids));
    }
}
